package demo

import (
	"fmt"
	"go.uber.org/zap"
	"goskeleton/app/core/db"
	"goskeleton/app/entity"
	"goskeleton/app/global/variable"
	"goskeleton/app/model"
	"goskeleton/app/utils/redis_factory"
)

func CreateDemoServiceFactory(sqlType string) *entity.User {
	return &entity.User{BaseModel: model.BaseModel{DB: model.UseDbConn(sqlType)}}
}

func DemoTest() (userList []*entity.User, err error) {

	//db := CreateDemoServiceFactory("mysql")
	if err := db.SqlSession.Find(&userList).Error; err != nil {
		fmt.Println("userList fail =========》userList", userList)
		return nil, err
	}
	fmt.Println("userList 成功ok=========》userList", userList)
	return
}

// ChangeDb 切换数据库
func ChangeDb(ds string) (flag string, err error) {
	// 从连接池获取一个连接
	redisClient := redis_factory.GetOneRedisClient()

	//  set 命令, 因为 set  key  value 在redis客户端执行以后返回的是 ok，所以取回结果就应该是 string 格式
	res, err := redisClient.String(redisClient.Execute("set", "db_code", ds))
	if err != nil {
		fmt.Printf("设置失败,%s\n", err.Error())
	} else {
		// 设置 SqlSession
		fmt.Println("设置成功", res)
		db.MysqlSession(ds)
		variable.ZapLog.Info("Info 日志", zap.String("db_code", res))
	}
	//  get 命令，分为两步：1.执行get命令 2.将结果转为需要的格式
	if res, err = redisClient.String(redisClient.Execute("get", "db_code")); err != nil {
		fmt.Printf("设置失败,%s\n", err.Error())
	}
	variable.ZapLog.Info("get db_code ", zap.String("db_code", res))
	//操作完毕记得释放连接，官方明确说，redis使用完毕，必须释放
	redisClient.ReleaseOneRedisClient()
	return res, err
}
